package com.example.androidhw03;

import java.util.HashMap;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;

public class TabManager implements OnTabChangeListener {

	private final FragmentActivity mActivity;
	private final TabHost mTabHost;
	private final int mContainerId;
	private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
	TabInfo mLastTab;
	
	private static class TabInfo{
		private final String tag;
		private final Class<?> clss;
		private final Bundle args;
		private Fragment fragment;
		
		TabInfo(String _tag, Class<?> _class, Bundle _args){
			tag = _tag;
			clss = _class;
			args = _args;
		}
	}
	
	private class DummyTabFactory implements TabContentFactory{
		private final Context mContext;
		
		public DummyTabFactory(Context context){
			mContext = context;
		}

		@Override
		public View createTabContent(String tag) {
			// TODO Auto-generated method stub
			View v = new View(mContext);
			v.setMinimumHeight(0);
			v.setMinimumWidth(0);
			return v;
		}
	}
	
	public TabManager(FragmentActivity activity, TabHost tabHost, int containerId){
		mActivity = activity;
		mTabHost = tabHost;
		mContainerId = containerId;
		mTabHost.setOnTabChangedListener(this);
	}
	
	public void addTab(TabSpec tabSpec, Class<?> clss, Bundle args){
		tabSpec.setContent(new DummyTabFactory(mActivity));
		String tag = tabSpec.getTag();
		
		TabInfo info = new TabInfo(tag, clss, args);
		
		info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
		if(info.fragment != null && !info.fragment.isDetached()){
			FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
			ft.detach(info.fragment);
			ft.commit();
		}
		
		mTabs.put(tag, info);
		mTabHost.addTab(tabSpec);
	}
	
	@Override
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		TabInfo newTab = mTabs.get(tabId);
		if(mLastTab != newTab){
			FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
			
			if(mLastTab != null){
				if(mLastTab.fragment != null){
					ft.detach(mLastTab.fragment);
				}
			}
			
			if(newTab != null){
				if(newTab.fragment == null){
					newTab.fragment = Fragment.instantiate(mActivity, newTab.clss.getName(), newTab.args);
					ft.add(mContainerId, newTab.fragment, newTab.tag);
				}else{
					ft.attach(newTab.fragment);
				}
			}
			
			mLastTab = newTab;
			ft.commit();
			mActivity.getSupportFragmentManager().executePendingTransactions();
		}
	}

}
